//
//  MCSendToPersonViewController.m
//  XDYL
//
//  Created by menhao on 2018/3/21.
//  Copyright © 2018年 TLYL01. All rights reserved.
//

#import "MCSendToPersonViewController.h"
#import "UIImage+Extension.h"
#import <MJRefresh/MJRefresh.h>
#import "MCRefreshNormalHeader.h"
#import "MCPersonHongBaoModel.h"
#import "MCBreadcrumbTrailView.h"
#import "MCHongBaoButton.h"
#import "MCHongBaoPersonTableViewCell.h"
#import "MCRedBagSearchTVController.h"
#import "AppDelegate.h"
#import "MCSendListNameModel.h"

static NSMutableArray *_slectedDataArray;
@interface MCSendToPersonViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchBarDelegate>
@property (nonatomic,strong) MCBreadcrumbTrailView *trailView;
@property (nonatomic,weak) UIButton *lastBtn;

@property (nonatomic,strong) MCPersonHongBaoModel *personHongModel;
@property (nonatomic,strong) NSMutableArray *responeDataArray;
@property (nonatomic,strong) NSMutableArray *levelDataArray;
@property (nonatomic,strong) NSString *userId;
@property (nonatomic,strong) MCPersonHongBaoModel *lastModel;
@property (nonatomic,strong) MCPersonHongBaoModel *selectedModel;

@property (nonatomic,assign) int type;

@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) MCRedBagSearchTVController *searchVC;

//tableView
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataListArry;
@property (strong, nonatomic) UIButton *btn1;
@property (strong, nonatomic) UIButton *btn2;
@property (strong, nonatomic) UIButton *btn3;

@end

@implementation MCSendToPersonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发送对象";
    self.navigationController.navigationBar.barTintColor = RGB(255, 69, 69);
    self.view.backgroundColor = RGB(240, 240, 240);
    
    [self setUpSegmentControl];
    [self setUpNaviButton];
    [self setUpTabView];
    [self loadListData];
    
    [self initSearchController];

}

- (void)initSearchController{

    
    self.searchVC = [[MCRedBagSearchTVController alloc]init];
    self.searchVC.type = self.type;
    //创建UISearchController
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchVC];
    self.searchController.searchResultsController.view.hidden = NO;
    self.searchController.view.backgroundColor = [UIColor whiteColor];
    self.searchController.searchResultsUpdater = self.searchVC;
    self.searchController.delegate = self;
    self.searchController.searchBar.delegate = self;
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.placeholder = @"搜索";

    
    //包着搜索框外层的颜色
    self.searchController.searchBar.tintColor = RGB(46, 46, 46);
    self.searchController.searchBar.barTintColor = [UIColor whiteColor];
    self.searchController.searchBar.layer.borderColor = [UIColor darkGrayColor].CGColor;
    UIView *v = [self.searchController.searchBar valueForKeyPath:@"_searchField"];
    v.layer.borderWidth = 0.5;
    v.layer.cornerRadius = 6;
    v.clipsToBounds = YES;
    v.layer.borderColor = [UIColor darkGrayColor].CGColor;
    
    
    //搜索时，背景变暗色
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.y = MC_REALVALUE(40);
    self.definesPresentationContext = YES;
    self.searchVC.nav = self.navigationController;
    self.searchVC.searchBar = self.searchController.searchBar;
    [self.view addSubview:self.searchController.searchBar];


}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = RGB(255, 69, 69);
    [self addNotification];
    self.type = [[[NSUserDefaults standardUserDefaults]objectForKey:@"type_hongbao"] intValue];
    if (self.type == 0) {
        self.type = 1;
        [[NSUserDefaults standardUserDefaults] setObject:@(1) forKey:@"type_hongbao"];
        
    }
    if (self.type == 1) {
        self.btn1.selected = YES;
        
    } else if (self.type == 2) {
        self.btn2.selected = YES;
    }else if (self.type == 3){
        self.btn3.selected = YES;
    }
    [self loadListData];
    self.userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
  
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.barTintColor = RGB(45,169,223);

    [self.slectedDataArray removeAllObjects];
    [SVProgressHUD dismiss];
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)addNotification{
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(redBagSearchUserNameNoti:) name:@"RedBagSearchUserNameNotification" object:nil];
}


- (void)setUpSegmentControl{
    NSArray *arr = @[@"整个团队",@"直属下级",@"单个对象"];
    //条件选择
    for (NSInteger i = 0; i<arr.count; i++) {
        MCHongBaoButton *btn = [[MCHongBaoButton alloc] init];
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        [self.view addSubview:btn];
        btn.frame = CGRectMake(20 + (G_SCREENWIDTH - 40 - 96) / arr.count * i + 48 *i,7, MC_REALVALUE(80), MC_REALVALUE(25));
        if (i == 0) {
            [btn setImage:[UIImage imageNamed:@"zgtd0"] forState:UIControlStateNormal];
            self.btn1 = btn;
        } else if(i == 1){
            [btn setImage:[UIImage imageNamed:@"zsxj0"] forState:UIControlStateNormal];
            self.btn2 = btn;
        }else{
            [btn setImage:[UIImage imageNamed:@"dgxj"] forState:UIControlStateNormal];
            self.btn3 = btn;
        }
        
        [btn setBackgroundImage:[UIImage createImageWithColor:RGB(255,69,69)] forState:UIControlStateSelected];
        [btn setBackgroundImage:[UIImage createImageWithColor:RGB(201, 201, 201)] forState:UIControlStateNormal];
        btn.layer.cornerRadius = 6;
        btn.clipsToBounds = YES;
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

        btn.tag = i + 1000;
        [btn addTarget:self action:@selector(segmentContrlBtnClick:) forControlEvents:UIControlEventTouchDown];
        
        //默认 第一个
        if (i==0) {
            
            self.lastBtn=btn;
        }
    }
    

    
}

- (void)setUpNaviButton{
    /*
     * 完成按钮
     */
    UIButton *btn = [[UIButton alloc] init];
    [btn setTitle:@"完成" forState:UIControlStateNormal];
    [btn sizeToFit];
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    [btn addTarget:self action:@selector(naviButtonClick) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)segmentContrlBtnClick:(UIButton *)btn{
    self.lastBtn.selected = NO;
    self.btn1.selected = NO;
    self.btn2.selected = NO;
    self.btn3.selected = NO;
    btn.selected = YES;
    self.lastBtn = btn;
    
    [self.tableView reloadData];
    self.type = (int)btn.tag - 1000 + 1;
    [[NSUserDefaults standardUserDefaults] setObject:@(self.type) forKey:@"type_hongbao"];
    self.searchVC.type = self.type;
    
    
    
    if (self.type == 3) {
      MCPersonHongBaoModel *m = self.slectedDataArray.lastObject;
        if (m.UserID == [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"]) {
            _slectedDataArray = nil;
            
            for (MCPersonHongBaoModel *mode in self.responeDataArray) {
                mode.selected = NO;
            }
            
            [self.tableView reloadData];
        }
        [SVProgressHUD showInfoWithStatus:@"发给所选人"];
    }else if (self.type == 2){
        [SVProgressHUD showInfoWithStatus:@"发给所选人的直属下级"];
    }else{
        [SVProgressHUD showInfoWithStatus:@"发给所选人的整个团队"];
    }
    self.userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
 
    [self loadListData];
    NSMutableArray *temp1 = [NSMutableArray array];
    [self.levelDataArray removeObjectsInRange:NSMakeRange(1, self.levelDataArray.count -1)];
    for (MCPersonHongBaoModel *m in self.levelDataArray) {
        [temp1 addObject:m.ChildUserName];
    }
    self.trailView.dataArr = temp1;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedBreadcrumbTrailBlock" object:nil];

}

- (void)setUpTabView{
    NSMutableArray *temp = [NSMutableArray array];

    for (MCPersonHongBaoModel *m in self.levelDataArray) {
        [temp addObject:m.ChildUserName];
    }

    MCBreadcrumbTrailView *trailView = [[MCBreadcrumbTrailView alloc] initWithFrame:CGRectMake(0, MC_REALVALUE(96), G_SCREENWIDTH, MC_REALVALUE(30))];//96
    trailView.backgroundColor = RGB(255, 255, 255);
    self.trailView = trailView;
    self.trailView.dataArr = temp;
    trailView.selectedBreadcrumbTrailBlock = ^(NSInteger i) {
     
    [self.levelDataArray removeObjectsInRange:NSMakeRange((i + 1) , self.levelDataArray.count - i -1)];
       MCPersonHongBaoModel *m = self.levelDataArray[i];
        self.lastModel = m;
        self.userId = [NSString stringWithFormat:@"%d",m.User_ID];
        if (i == 0) {
            self.userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
            
        }
         [self loadListData];
          NSMutableArray *temp1 = [NSMutableArray array];
        for (MCPersonHongBaoModel *m in self.levelDataArray) {
            [temp1 addObject:m.ChildUserName];
        }
         self.trailView.dataArr = temp1;
        // 清除数组
        [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedBreadcrumbTrailBlock" object:nil];
//        刷新页面
        
    };
    [self.view addSubview:trailView];
    UITableView *tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, MC_REALVALUE(30 + 40 + 56), G_SCREENWIDTH , G_SCREENHEIGHT - kStatusBarAndNavigationBarHeight - MC_REALVALUE(30 + 40 + 56)) style:UITableViewStylePlain];// + 56
    [self.view addSubview:tabView];
    tabView.delegate = self;
    tabView.dataSource = self;
    self.tableView = tabView;
    tabView.rowHeight = MC_REALVALUE(52);
    tabView.backgroundColor = [UIColor whiteColor];
    [tabView registerClass:[MCHongBaoPersonTableViewCell class] forCellReuseIdentifier:@"hongBaocell"];

    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
    for (id obj in [searchBar subviews]) {
        if ([obj isKindOfClass:[UIView class]]) {
            for (id obj2 in [obj subviews]) {
                if ([obj2 isKindOfClass:[UIButton class]]) {
                    UIButton *btn = (UIButton *)obj2;
                    [btn setTitle:@"取消" forState:UIControlStateNormal];
                }
            }
        }
    }
    return YES;
}



#pragma mark - UISearchControllerDelegate代理
//测试UISearchController的执行过程

#pragma mark - UISearchControllerDelegate代理

- (void)didDismissSearchController:(UISearchController *)searchController {
  
    self.tableView.tableHeaderView = nil;
    self.searchController.searchBar.y = MC_REALVALUE(40);
    self.tableView.frame = CGRectMake(0, MC_REALVALUE(30 + 40 + 56), G_SCREENWIDTH , G_SCREENHEIGHT - kStatusBarAndNavigationBarHeight - MC_REALVALUE(30 + 40 + 56));
    [self.view addSubview:self.searchController.searchBar];

 
}

- (void)presentSearchController:(UISearchController *)searchController {
    self.searchVC.type = self.type;
    self.tableView.tableHeaderView = self.searchController.searchBar;
    self.tableView.y = 0;
    self.tableView.frame = CGRectMake(0, MC_REALVALUE(0), G_SCREENWIDTH , G_SCREENHEIGHT - kStatusBarAndNavigationBarHeight);
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.responeDataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MCHongBaoPersonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hongBaocell"];
    MCPersonHongBaoModel *m = self.responeDataArray[indexPath.row];

    cell.type = 0;
    cell.btn.hidden = NO;
    if (indexPath.row == 0) {
        cell.isSelf = YES;
    } else {
        cell.isSelf = NO;
    }
    if (self.type == 1) {
        cell.imageV.hidden = YES;
    } else  if (self.type == 2){
        cell.imageV.hidden = YES;
    }else{
        
            if (indexPath.row == 0) {
                if (self.userId == [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"]) {
                     cell.type = 3;
                } 
                cell.imageV.hidden = YES;
                cell.btn.hidden = YES;

        } else {
            cell.btn.hidden = NO;
            if (m.LevelNum ==0) {
                cell.imageV.hidden = YES;
            } else {
//                cell.type = 3;
                cell.imageV.hidden = NO;
            }
            
        }
    }
 
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.selectedPersonBlock = ^(MCPersonHongBaoModel *selected) {
        for (MCPersonHongBaoModel *mode in self.responeDataArray) {
            mode.selected = NO;
            if (mode == selected) {
                mode.selected = YES;
                self.selectedModel = mode;
            }
        }
        if (selected.User_ID == 0) {
            selected.User_ID = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
        }
        [self.tableView reloadData];
      
        _slectedDataArray = [NSMutableArray arrayWithArray:@[selected]];
        
        
    };
    cell.unSelectedPersonBlock = ^(MCPersonHongBaoModel *m) {
        self.selectedModel = nil;
    };
    cell.dataSource = self.responeDataArray[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.lastBtn.tag == 1002) {
        if (indexPath.row == 0) {
            return;
        }
        MCPersonHongBaoModel  *model = self.responeDataArray[indexPath.row];
        self.lastModel = model;
         NSMutableArray *temp = [NSMutableArray array];
            if (model.LevelNum > 0) {
                self.userId = [NSString stringWithFormat:@"%d",model.User_ID];
                [self loadListData];
                // 如果有下级 ，添加到数组
                
                if (![self.levelDataArray containsObject:model]) {
                    [self.levelDataArray addObject:model];
                    //    刷新collecitonview
                   
                    for (MCPersonHongBaoModel *m in self.levelDataArray) {
                        [temp addObject:m.ChildUserName];
                    }
                    self.trailView.dataArr = temp;
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedBreadcrumbTrailBlock" object:nil];
                }
            }
    }else{
        [self.levelDataArray removeObjectsInRange:NSMakeRange(1, self.levelDataArray.count - 1)];
    }
}
- (void)loadListData{
    MCPersonHongBaoModel *personHongModel = [[MCPersonHongBaoModel alloc]init];
    self.personHongModel = personHongModel;
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    if (![self.userId isEqualToString:@""]&&self.userId != nil) {
        self.personHongModel.UserID = self.userId;
    }else{
        self.personHongModel.UserID = userId;
    }
    [BKIndicationView showInView:self.view];
    [personHongModel refreashDataAndShow];
    __weak __typeof(self)wself = self;
    personHongModel.callBackSuccessBlock = ^(NSDictionary *manager) {
        [BKIndicationView dismiss];
        
        [wself.responeDataArray removeAllObjects];
        NSMutableArray *aryM = [MCPersonHongBaoModel mj_objectArrayWithKeyValuesArray:manager[@"GetUserModel"]];
        
        if (self.type == 3 || self.type == 1) {
            wself.responeDataArray = aryM;
        } else {
            for (MCPersonHongBaoModel *m in aryM) {
                if ((m.Category & 64) != 64) {
                    [wself.responeDataArray addObject:m];
                }
            }
            
        }

        
        if (wself.responeDataArray.count > 0 || self.type == 1) {
            MCPersonHongBaoModel *model = [[MCPersonHongBaoModel alloc] init];
            model.UserID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
            model.ChildUserName = [[NSUserDefaults standardUserDefaults]objectForKey:@"UserName"];
            if (![self.userId isEqualToString:userId]&&self.userId != nil) {
                model = self.lastModel;
            }
            [wself.responeDataArray insertObject:model atIndex:0];
        }

        for (MCPersonHongBaoModel *model1 in wself.responeDataArray) {
            if (model1.User_ID == self.selectedModel.User_ID && self.selectedModel.User_ID != 0) {
                model1.selected = YES;
            } else {
                model1.selected = NO;
            }
        }
        [self.tableView reloadData];
    };
    personHongModel.callBackFailedBlock = ^(id manager, NSDictionary *errorCode) {
        [BKIndicationView dismiss];
    };
}


- (void)naviButtonClick{
    
    [self sendDataToSendRedBagVC:self.slectedDataArray.lastObject];
}

- (void)redBagSearchUserNameNoti:(NSNotification *)noti{
    
    MCSendListNameModel *model = noti.object;
    MCPersonHongBaoModel *selected = [[MCPersonHongBaoModel alloc] init];
    selected.ChildUserName = model.UserName;
    selected.User_ID = [model.UserId intValue];
    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserName"];
    int type_hongbao = [[[NSUserDefaults standardUserDefaults] objectForKey:@"type_hongbao"] intValue];
    
    if (type_hongbao == 3 && [model.UserName isEqualToString:name]) {
        selected = nil;
        [SVProgressHUD showInfoWithStatus:@"单个对象不能选择自己！"];
        return;
    }
    if (!(self.type != 3 && (selected.Category & 64) == 64)) {
        if (self.selectedPersonBlock) {
            self.selectedPersonBlock(selected,self.type);
        }
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sendDataToSendRedBagVC:(MCPersonHongBaoModel *)selected{
    if (selected.selected == NO ) {
        [SVProgressHUD showInfoWithStatus:@"请选择发送对象"];
        return;
    }
    
    if (!(self.type != 3 && (selected.Category & 64) == 64)) {
        if (self.selectedPersonBlock) {
            self.selectedPersonBlock(selected,self.type);
        }
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark getter and setter 
- (NSMutableArray *)slectedDataArray{
    if (_slectedDataArray == nil) {
        _slectedDataArray = [NSMutableArray array];
    }
    return _slectedDataArray;
}
- (NSMutableArray *)levelDataArray{
    if (_levelDataArray == nil) {
        _levelDataArray = [NSMutableArray array];
        MCPersonHongBaoModel *m = [[MCPersonHongBaoModel alloc] init];
        m.ChildUserName = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserName"];
        m.UserID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
        [_levelDataArray addObject:m];
    }
    return _levelDataArray;
}
- (NSMutableArray *)responeDataArray{
    if (_responeDataArray == nil) {
        _responeDataArray = [NSMutableArray array];
    }
    return _responeDataArray;
}
@end
